/*
 * Copyright (C) 2017 Pingan, Inc. All Rights Reserved.
 */

package com.pingan.haofang.searchcloud.index.service.impl;

import com.pingan.haofang.searchcloud.api.constants.EngineType;
import com.pingan.haofang.searchcloud.common.configuration.ClusterProperties;
import com.pingan.haofang.searchcloud.index.service.ClusterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 集群信息实现
 *
 * @author zhangbi617
 * @date 2017-07-19
 */
@Service
public class ClusterServiceImpl implements ClusterService {

    @Autowired
    private ClusterProperties clusterProperties;

    @Override
    public Map<EngineType, List<ClusterProperties.ClusterInfo>> getClusterInfo() {
        Map<EngineType, List<ClusterProperties.ClusterInfo>> result = new LinkedHashMap<>();

        for (ClusterProperties.ClusterInfo clusterInfo : clusterProperties.getServers()) {
            List<ClusterProperties.ClusterInfo> list = result.getOrDefault(clusterInfo.getEngineType(), new ArrayList<>());
            list.add(clusterInfo);
            result.put(clusterInfo.getEngineType(), list);
        }

        return result;
    }

    @Override
    public Map<String, ClusterProperties.ClusterInfo> getClusterMap(EngineType engineType) {
        Map<String, ClusterProperties.ClusterInfo> result = new LinkedHashMap<>();

        List<ClusterProperties.ClusterInfo> list = getClusterInfo().get(engineType);
        for (ClusterProperties.ClusterInfo clusterInfo : list) {
            result.put(clusterInfo.getName(), clusterInfo);
        }
        return result;
    }

    @Override
    public Map<String, ClusterProperties.ClusterInfo> getHostKeyClusterMap(EngineType engineType) {
        Map<String, ClusterProperties.ClusterInfo> result = new LinkedHashMap<>();

        List<ClusterProperties.ClusterInfo> list = getClusterInfo().get(engineType);
        for (ClusterProperties.ClusterInfo clusterInfo : list) {
            result.put(clusterInfo.getHost(), clusterInfo);
        }
        return result;
    }
}
